Remove duplicates from sorted array II [Two Pointers]¶
Time: O(N); Space: O(1); medium
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: nums = [1,1,1,2,2,3]
Output: 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
Example 2:
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
Notes:
It doesn’t matter what values are set beyond the returned length.
Clarification:¶
Confused why the returned value is an integer but your answer is an array? Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this: //nums is passed in by reference. (i.e., without making a copy) len = removeDuplicates(nums) //any modification to nums in your function would be known by the caller. //using the length returned by your function, it prints the first len elements. for i in range(len): print(nums[i])
[3]:
class Solution1(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
last, i, same = 0, 1, False
while i < len(nums):
if nums[last] != nums[i] or not same:
same = nums[last] == nums[i]
last += 1
nums[last] = nums[i]
i += 1
return last + 1
[4]:
s = Solution1()
nums = [1, 1, 1, 2, 2, 3]
assert s.removeDuplicates(nums) == 5
print(nums[:5])
nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]
assert s.removeDuplicates(nums) == 7
print(nums[:7])
[1, 1, 2, 2, 3]
[0, 0, 1, 1, 2, 3, 3]